package org.lzy.shop.activity

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.os.Build
import android.util.Log
import android.view.KeyEvent
import android.webkit.WebChromeClient
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import org.lzy.shop.R
import org.lzy.shop.base.BaseActivity
import org.lzy.shop.databinding.ActivityWebviewBinding

/**
 * WebView页面，用于显示隐私政策和服务条款等内容
 */
class WebViewActivity : BaseActivity<ActivityWebviewBinding>({ ActivityWebviewBinding.inflate(it) }) {

    companion object {
        private const val TAG = "WebViewActivity"
        // 传递的参数键名
        const val KEY_TITLE = "title"
        const val KEY_URL = "url"
        const val KEY_LOCAL_FILE = "local_file"

        // 本地文件名称
        const val FILE_PRIVACY_POLICY = "privacy_policy.html"
        const val FILE_TERMS_OF_SERVICE = "terms_of_service.html"
    }

    override fun initView() {
        // 获取传递的标题和URL/文件
        val title = intent.getStringExtra(KEY_TITLE) ?: getString(R.string.app_name)
        val url = intent.getStringExtra(KEY_URL)
        val localFile = intent.getStringExtra(KEY_LOCAL_FILE)

        // 设置标题
        setTitleText(title)

        // 设置WebView
        setupWebView()

        // 加载内容
        if (!url.isNullOrEmpty()) {
            binding.webView.loadUrl(url)
        } else if (!localFile.isNullOrEmpty()) {
            // 加载本地HTML文件
            val fileUrl = "file:///android_asset/${localFile}"
            binding.webView.loadUrl(fileUrl)
        }
    }

    override fun initData() {
    }

    override fun requestData() {
    }

    override fun allClick() {
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun setupWebView() {
        // 配置WebView设置
        val webSettings = binding.webView.settings

        // 启用JavaScript（如果需要）
        webSettings.javaScriptEnabled = true
        // 设置JS接口安全模式
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            webSettings.javaScriptCanOpenWindowsAutomatically = false
        }

        // 设置支持缩放
        webSettings.setSupportZoom(true)
        webSettings.builtInZoomControls = true
        webSettings.displayZoomControls = false
        webSettings.textZoom = 100

        // 混合内容处理（更安全的设置）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // 只在HTTPS页面允许加载HTTP内容，更安全
            webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
        }

        // 优化缓存策略
        webSettings.cacheMode = WebSettings.LOAD_DEFAULT
        webSettings.domStorageEnabled = true
        webSettings.databaseEnabled = true


        // 优化渲染
        webSettings.loadsImagesAutomatically = true
        webSettings.useWideViewPort = true
        webSettings.loadWithOverviewMode = true

        // 设置WebViewClient以处理页面加载
        binding.webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
                // 在WebView中加载URL，而不是打开外部浏览器
                if (request != null) {
                    val url = request.url.toString()
                    // 可以在这里添加URL过滤逻辑，例如某些链接需要在外部浏览器打开
                    view?.loadUrl(url)
                }
                return true
            }

            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                // 显示加载进度条

            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                // 隐藏加载进度条
            }

            override fun onReceivedError(view: WebView?, request: WebResourceRequest?, error: WebResourceError?) {
                super.onReceivedError(view, request, error)
                // 处理加载错误
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    val errorMessage = "加载失败: ${error?.description}"
                    Toast.makeText(this@WebViewActivity, errorMessage, Toast.LENGTH_SHORT).show()
                    Log.e(TAG, "WebView加载错误: $errorMessage")
                }
            }
        }

        // 设置WebChromeClient以处理进度更新等
        binding.webView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                // 更新进度条

            }
        }
    }

    // 处理返回键事件
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        // 如果WebView可以返回上一页，则返回上一页而不是关闭Activity
        if (keyCode == KeyEvent.KEYCODE_BACK && binding.webView.canGoBack()) {
            binding.webView.goBack()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    // 处理生命周期事件
    override fun onPause() {
        super.onPause()
        // 在API 11及以上版本中，暂停WebView的JavaScript执行
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            binding.webView.onPause()
        }
    }

    override fun onResume() {
        super.onResume()
        // 在API 11及以上版本中，恢复WebView的JavaScript执行
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            binding.webView.onResume()
        }
    }

    override fun onDestroy() {
        try {
            // 1. 首先清除WebView的所有回调和设置
            binding.webView.webChromeClient = null
            binding.webView.clearHistory()
            binding.webView.clearCache(true)
            binding.webView.clearFormData()

            // 2. 停止所有JavaScript执行和加载
            binding.webView.stopLoading()
            binding.webView.loadUrl("about:blank")

            // 3. 从父容器中移除WebView
            val parent = binding.webView.parent
            if (parent is android.view.ViewGroup) {
                parent.removeView(binding.webView)
            }

            // 4. 最后销毁WebView
            binding.webView.destroy()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        
        super.onDestroy()
    }

    // 可选：添加一个清理WebView的方法，在需要时调用
    fun clearWebViewState() {
        binding.webView.stopLoading()
        binding.webView.loadUrl("about:blank")
    }
}